package com.wjjun.customview.views.dropdownmenu;

import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.wjjun.customview.R;

/**
 * dropDownMenu
 * Created by wjjun on 2018/5/21.
 */
public class DropDownMenu extends RelativeLayout {

    //顶部菜单布局
    private LinearLayout menuBar;
    //菜单栏背景颜色
    private int menuBackgroundColor = 0xffffff;

    //底部容器，包含popupMenuViews，maskView
    private FrameLayout containerView;
    //弹出菜单父布局
    private FrameLayout popupMenuViews;

    private View contentView;

    //遮罩颜色
    private int maskColor = 0x88888888;

    //tabMenuView里面选中的tab位置，-1表示未选中
    private int currentTabIndex = -1;

    private MenuAdapter menuAdapter;
    private OnItemMenuClickListener itemMenuClickListener;

    private int containerMarginTop = 0;


    public DropDownMenu(Context context) {
        super(context, null);
    }

    public DropDownMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DropDownMenu);

        menuBackgroundColor = a.getColor(R.styleable.DropDownMenu_ddm_menuBackgroundColor, menuBackgroundColor);
        maskColor = a.getColor(R.styleable.DropDownMenu_ddm_maskColor, maskColor);
        containerMarginTop = a.getDimensionPixelOffset(R.styleable.DropDownMenu_ddm_container_margin_top, 0);

        a.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initViews();
    }

    private void initViews() {
        contentView = findViewById(R.id.contentView);
        if (contentView == null) {
            contentView = getChildAt(0);
        }

        //先清空所有view
        removeAllViews();

        initMenuBar();

        if (contentView != null) {
            LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.addRule(BELOW, R.id.menu_bar);
            params.setMargins(0, containerMarginTop, 0,0);
            addView(contentView, params);
        }

        initContainerView();
    }

    private void initMenuBar() {
        //初始化tabMenuView并添加到tabMenuView
        menuBar = new LinearLayout(getContext());
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT);
        menuBar.setOrientation(LinearLayout.HORIZONTAL);
        menuBar.setBackgroundColor(menuBackgroundColor);
        menuBar.setLayoutParams(params);
        menuBar.setId(R.id.menu_bar);
        addView(menuBar);

    }

    private void initContainerView() {

        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(BELOW, R.id.menu_bar);

        //初始化containerView并将其添加到DropDownMenu
        containerView = new FrameLayout(getContext());

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams
                .MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        containerView.setLayoutParams(layoutParams);

        containerView.setBackgroundColor(maskColor);
        containerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeMenu();
            }
        });
        addView(containerView, params);

        popupMenuViews = new FrameLayout(getContext());
        popupMenuViews.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams
                .MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
        popupMenuViews.setBackgroundColor(Color.WHITE);
        containerView.addView(popupMenuViews);

        containerView.setVisibility(GONE);
        popupMenuViews.setVisibility(GONE);
    }


    public void setMenuAdapter(MenuAdapter adapter) {
        if (adapter == null) {
            return;
        }
        this.menuAdapter = adapter;
        menuAdapter.bindListener(new OnFilterDoneListener() {
            @Override
            public void onFilterDone(int position, Object value1, Object value2) {
                closeMenu();
                if (itemMenuClickListener != null) {
                    itemMenuClickListener.onContentItemClick(position, value1, value2);
                }
            }
        });


        menuAdapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                setMenuViews();
            }

            @Override
            public void onInvalidated() {
                setMenuViews();
            }
        });

        setMenuViews();

    }

    void setMenuViews() {
        menuBar.removeAllViews();
        int count = menuAdapter.getCount();
        for (int i = 0; i < count; i++) {
            addTab(i);
        }
    }

    private void addTab(final int index) {
        if (menuAdapter == null) {
            return;
        }

        final View tabView = menuAdapter.getMenuItemView(index, menuBar);

        float itemWeight = menuAdapter.getItemWeight(index);
        if (itemWeight <= 0) {
            tabView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
        } else {
            tabView.setLayoutParams(new LinearLayout.LayoutParams(0,
                    ViewGroup.LayoutParams.WRAP_CONTENT, itemWeight));
        }

        menuBar.addView(tabView);
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemMenuClickListener != null) {
                    itemMenuClickListener.onMenuItemClick(index);
                }
                switchMenu(index);
            }
        });
    }

    /**
     * DropDownMenu是否处于可见状态
     *
     * @return
     */
    public boolean isShowing() {
        return popupMenuViews.getVisibility() == VISIBLE;
    }

    /**
     * 切换菜单
     */
    private void switchMenu(int index) {
        if (currentTabIndex == index && isShowing()) {
            closeMenu();
        } else {
            openMenu(index);
        }
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        notifyMenuItemChange(currentTabIndex, false, true);

        popupMenuViews.setVisibility(View.GONE);
        popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim
                .menu_out));
        containerView.setVisibility(GONE);
        containerView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.mask_out));
    }


    private void openMenu(int index) {
        if (menuAdapter == null) {
            return;
        }
        View view = menuAdapter.getView(index, null, null);
        notifyMenuItemChange(currentTabIndex, false, false);
        currentTabIndex = index;
        notifyMenuItemChange(index, true, false);

        if (view == null) {
            if (isShowing()) {
                closeMenu();
            }
            return;
        }

        popupMenuViews.removeAllViews();
        popupMenuViews.setVisibility(View.VISIBLE);
        popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R
                .anim.menu_in));
        containerView.setVisibility(VISIBLE);
        containerView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim
                .mask_in));

        popupMenuViews.addView(view);
    }

    public void notifyMenuItemChange(int index, boolean isCheck, boolean isClose) {
        if (index < 0) {
            return;
        }
        View tabView = menuBar.getChildAt(index);
        menuAdapter.notifyItemChange(tabView, index, isCheck, isClose);
    }

    public void setOnItemMenuClickListener(OnItemMenuClickListener listener) {
        itemMenuClickListener = listener;
    }

    public int dp2Px(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5);
    }
}